package sporteam.web.server;
import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import sporteam.common.PMF;
import sporteam.web.client.AEuser;
import sporteam.web.client.Track;

import com.google.gson.Gson;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;

 

public class WriteUser extends HttpServlet
{
	
	private static final Logger MyLog = Logger.getLogger(UpdateUser.class.getName());
    private static final String SendLogURL = "http://sporteamws.appspot.com/SendLog";
	private static final long serialVersionUID = 1L;

	@Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException 
    {
		resp.setContentType("application/json");
		
		String facebookID = req.getParameter("facebook_id");
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		 
		Track t1 = new Track();
		Track t2 = new Track();
		Track t3 = new Track();
		
		t1.SetAvgSpeed(100);
		t2.SetCalories(200);
		t3.SetDistance(2020);
		
		AEuser user = createNewUser(facebookID);
		user.AddTrack(t1);
		user.AddTrack(t2);
		user.AddTrack(t3);
		JSONObject json =  userToJson(user);
 		 
		 //update user in appengine
		 pm.makePersistent(user);
		 
		 //close persistent manager
		 pm.close();
		 
		 resp.getWriter().write(json.toString());
         resp.getWriter().flush();
    }
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException
	{
	     
	}
	
	 private JSONObject userToJson(AEuser u) {
		 JSONObject j = new JSONObject();
         Gson g = new Gson();
         String s = g.toJson(u);
         try {
			j.put("JSONObject", s);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
         return j;
    }
	 
	 
	 
	 private AEuser createNewUser(String facebookID)
	 {
         FacebookClient facebookClient = new DefaultFacebookClient();
         com.restfb.types.User facebook_user = facebookClient.fetchObject(facebookID,
                         com.restfb.types.User.class);
         AEuser sporteamUser = new AEuser();
         String[] name = facebook_user.getName().split(" ");
         String first_name = name[0].trim();
         String last_name = name[1].trim();
         sporteamUser.SetFacebookID(facebookID);
         sporteamUser.SetFirstName(first_name);
         sporteamUser.SetLastName(last_name);

         return sporteamUser;
    }
	 
	

	 
	   
	   
	   
	
 
}